<template>
  <el-dialog title="资料上传" width="800"
    v-model="show"
    :show-close="false"
    @open="handleOpen"
  >
    <el-upload v-model:file-list="files"
      :action="cfg.uploadAction"
      :accept="props.accept"
      :limit="props.limit"
      :headers="headers"
      drag
      multiple
      :before-remove="handleRemove"
      :on-exceed="handleExceed"
    >
      <el-button type="primary">选择文件</el-button>
    </el-upload>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleSave">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox, type UploadUserFile } from 'element-plus'
import cfg from '@/config/config'
import { useUserStore } from '@/stores/user'
import { useEbookStore } from '@/stores/ebook'
import type { EbookCreateItem } from '@/config/types'

interface Props {
  lessonId: number
  limit?: number
  accept?: string
}

const show = defineModel()
const files = ref<UploadUserFile[]>([])
const props = withDefaults(defineProps<Props>(), {
  limit: 3,
  accept: "application/pdf"
})
const emit = defineEmits(['success'])
const headers = computed(() => {
  const store = useUserStore()
  return {
    appkey: cfg.appkey,
    Authorization: cfg.tokenHead + store.userInfo?.token
  }
})
const unCompleted = computed(() => {
  const len = files.value.filter((file : UploadUserFile) => file.status !== 'success').length
  return len > 0
})

const handleRemove = (uploadFile : UploadUserFile, uploadFiles : UploadUserFile[]) => {
  return ElMessageBox.confirm('确定要删除' + uploadFile.name + '吗?')
    .then(
      () => true, () => false
    )
}

const handleExceed = (files : File[], uploadFiles : UploadUserFile[]) => {
  ElMessage.warning('文件上传数量不能超过' + props.limit + '个')
}

const handleOpen = () => {
  files.value = []
}

const handleSave = async () => {
  if (unCompleted.value) {
    ElMessage.warning('文件上传中，请稍等')
    return
  }
  if (files.value.length > 0) {
    const store = useEbookStore()
    let results : EbookCreateItem[] = []
    files.value.forEach((f : UploadUserFile, idx: number) => {
      results.push({
        title: f.name,
        file: f.response?.data?.path,
        sort: idx + 1
      })
    })
    await store.createBatch(props.lessonId, results)
  }

  show.value = false
  emit('success')
}
</script>